package org.springblade.modules.oss.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.modules.oss.entity.Attach;
import org.springblade.modules.oss.entity.BackChunk;
import org.springblade.modules.oss.service.IAttachService;
import org.springblade.modules.oss.vo.AjaxResult;
import org.springblade.modules.oss.vo.CheckChunkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author YuTao
 * @date 2024-07-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/chunk")
@Api(value = "附件分片记录", tags = "附件分片记录接口")
public class BackFileController extends BladeController {
	protected AjaxResult toAjax(int rows)
	{
		return rows > 0 ? AjaxResult.success() : AjaxResult.error();
	}


	@Autowired
	private IAttachService attachService;



	/**
	 * 上传文件
	 */
	@ApiOperation("上传文件")
//	@PreAuthorize("@ss.hasPermi('system:file:upload')")
	@PostMapping("/upload")
	@SneakyThrows
	public AjaxResult postFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
	{
		int i = attachService.postFileUpload(chunk, response);
		AjaxResult aR = toAjax(i);
		if(aR.isSuccess()) {
			aR.put("needMerge", true);
			aR.put("result", true);
		}
		return aR;
	}

	/**
	 * 检查文件上传状态
	 */
	@ApiOperation("检查文件上传状态")
//	@PreAuthorize("@ss.hasPermi('system:file:check')")
	@GetMapping("/upload")
	public CheckChunkVO getFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
	{
		//查询根据md5查询文件是否存在
		CheckChunkVO fileUpload = attachService.getFileUpload(chunk, response);
		return fileUpload;
	}

	@ApiOperation("合并文件")
	//@PreAuthorize("@ss.hasPermi('system:file:merge')")
	@PostMapping("/merge")
	public R merge(Attach fileInfo)
	{
		String path = attachService.mergeFile(fileInfo);
		return R.data(path);
	}
}
